const url = require('url');
const got = require('@/utils/got');
const cheerio = require('cheerio');

module.exports = async (ctx) => {
    const root_url = 'https://photo.cctv.com/data/index.json';
    const response = await got({
        method: 'get',
        url: root_url,
    });

    const data = response.data;
    const list = data.rollData;

    const count = [];
    for (let i = 0; i < Math.min(list.length, 10); ++i) {
        count.push(i);
    }

    const items = await Promise.all(
        count.map((i) => {
            const item = list[i];
            const title = item.title;
            const link = item.url;

            const pubDate = new Date(item.dateTime + ':00 GMT+8').toUTCString();

            return ctx.cache.tryGet('tangshanribao_cctvphotos' + link, async () => {
                const res = await got({ method: 'get',
                    url: link.replace('.shtml', '.xml')
                });
                const content = cheerio.load(res.data, {xmlMode:true});
                const post = content('ul');

                const desc = post.find('li[photourl]').map((_, ele) => {
                    ele = content(ele);
                    return `<li><img src="${ele.attr('photourl')}" width="720" /><div>${ele.text()}</div></li>`
                }).toArray().join('');

                return {
                    title: title,
                    link: url.resolve(root_url, link),
                    pubDate,
                    description: `<ul>${desc}</ul>`,
                };
            });
        })
    );

    ctx.state.data = {
        title: '央视网 - 图片',
        link: root_url,
        item: items,
    };
};
